package model

import (
	"go-devops/dao"
	"go-devops/domain/dto"
)

type Secret struct {
	Id          int64  `json:"id" gorm:"primaryKey"`
	SecretType  string `json:"type" gorm:"column:type"`
	Name        string `json:"name"`
	SecretKey   string `json:"secretKey"`
	SecretValue string `json:"secretValue"`
	CreateTime  string `json:"createTime"`
}

func (Secret) TableName() string {
	return "secret"
}

func QuerySecretList(secretType string) (list []*Secret, err error) {
	if len(secretType) <= 0 {
		if err := dao.DB.Order("id desc").Find(&list).Error; err != nil {
			return nil, err
		}
	} else {
		if err := dao.DB.Where("type = ?", secretType).Order("id desc").Find(&list).Error; err != nil {
			return nil, err
		}
	}
	return list, err
}

func QuerySecretCount(addSecret *dto.AddSecretDTO) (count int64, err error) {
	err = dao.DB.Model(&Secret{}).Where("type = ? and name = ?", addSecret.SecretType, addSecret.Name).Count(&count).Error
	return count, err
}

func AddSecret(secret *Secret) (err error) {
	return dao.DB.Create(&secret).Error
}

func DeleteSecret(secretType string, name string) (err error) {
	return dao.DB.Where("type = ? and name = ?", secretType, name).Delete(&Secret{}).Error
}

func QuerySecretByNameAndType(secretType string, name string) (secret *Secret, err error) {
	if err := dao.DB.Where("type = ? and name = ?", secretType, name).First(&secret).Error; err != nil {
		return nil, err
	}
	return secret, nil
}
